package com.session2;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class JFileChooserDemo extends JFrame implements ActionListener {
	private JButton btnFile;
	private JFileChooser fChoose;
	public JFileChooserDemo() {
		
	}
	public void createForm(){
		this.setLayout(new FlowLayout());
		this.btnFile = new JButton("Brower...");
		this.getContentPane().add(this.btnFile);
		this.btnFile.addActionListener(this);
	}
	public void showForm(){
		this.setTitle("JFlieChoose Demo");
		this.setSize(400,300);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setVisible(true);
	}
	public static void main(String[] args) {
		JFileChooserDemo d = new JFileChooserDemo();
		d.createForm();
		d.showForm();
	}
	@Override
	public void actionPerformed(ActionEvent e) {
		if(e.getSource() == this.btnFile){
			this.fChoose = new JFileChooser();
			this.fChoose.setFileFilter(new MyFileFilter());
//			int result = this.fChoose.showSaveDialog(this);
//			if(result == JFileChooser.APPROVE_OPTION){
//				File f = fChoose.getSelectedFile();
//				try {
//					PrintWriter out = new PrintWriter(f);
//					out.print("Xin Chao!");
//					out.close();
//				} catch (FileNotFoundException e1) {
//					e1.printStackTrace();
//				}
//			}
			int reult = this.fChoose.showOpenDialog(this);
			if(reult == JFileChooser.CANCEL_OPTION){
				JOptionPane.showMessageDialog(this, "Cancel");
			}else if(reult == JFileChooser.OPEN_DIALOG){
				File f = this.fChoose.getSelectedFile();
				try {
					FileInputStream fin = new FileInputStream(f);
					byte [] b = new byte[fin.available()];
					fin.read(b);
					String str = new String(b);
					JOptionPane.showMessageDialog(this, str);
				} catch (FileNotFoundException e1) {
					e1.printStackTrace();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		}
	}

}
